package com.itheima.dao;

import com.itheima.domain.Customer;
import com.itheima.domain.Linkman;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import javax.xml.transform.Transformer;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Mr.King on 2017/2/28.
 */

public class QueryDao extends HibernateDaoSupport {

    public List findCustomer(Customer customer){
        //SQL拼接
        
        //1.创建离线对象
        DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
        if (customer.getCustName() != null && !"".equals(customer.getCustName())){
            criteria.add(Restrictions.eq("custName",customer.getCustName()));
        }else if (customer.getCustLevel() != null && !"".equals(customer.getCustLevel())){
            criteria.add(Restrictions.eq("custLevel",customer.getCustLevel()));
        }else if (customer.getCustSource() != null && !"".equals(customer.getCustSource())){
            criteria.add(Restrictions.eq("custSource",customer.getCustSource()));
        }
        return this.getHibernateTemplate().findByCriteria(criteria);
    }

    public List findLinkman(Linkman linkman, List<Integer> cids) {
        //离线查询
        DetachedCriteria criteria = DetachedCriteria.forClass(Linkman.class);

        if (cids != null && cids.size() > 0){
            criteria.add(Restrictions.in("customer.cid",cids.toArray()));
        }else if (linkman.getLkmName() != null && !"".equals(linkman.getLkmName())){
            criteria.add(Restrictions.eq("lkmName",linkman.getLkmName()));
        }else if (linkman.getLkmGender() != null && !"".equals(linkman.getLkmGender())){
            criteria.add(Restrictions.eq("lkmGender",linkman.getLkmGender()));
        }
        return this.getHibernateTemplate().findByCriteria(criteria);
    }

    public List countIndustry() {
//        Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
        Session session = this.getSessionFactory().getCurrentSession();
        String sql = "select count(1) num,custIndustry from customer group by custIndustry";

        SQLQuery query = session.createSQLQuery(sql);
        //封装成对象
//        query.addEntity(Customer.class);
        //把list集合结构变成map集合返回
        return query.setResultTransformer(Transformers.aliasToBean(HashMap.class)).list();
    }

    public List statisticsSource() {
        Session session = this.getSessionFactory().getCurrentSession();

        String sql = "select count(1) num,custSource from customer group by custSource";

        SQLQuery query = session.createSQLQuery(sql);

//        query.addEntity(Customer.class);

        return query.setResultTransformer(Transformers.aliasToBean(HashMap.class)).list();
    }
}
